package com.yq.master.controller;

import com.google.common.collect.Maps;
import com.yq.core.base.service.BaseService;
import com.yq.core.constant.Constant;
import com.yq.core.entity.SysUserEntity;
import com.yq.core.service.SysPowerService;
import com.yq.core.service.SysUserService;
import com.yq.core.util.MD5Util;
import com.yq.core.util.Result;
import com.yq.master.annotation.AzerothAutowired;
import com.yq.master.bean.WebUserBean;
import com.yq.master.staticdata.StaticData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;


/**
 * 信  息: [yinquan] [2017-03-04] [1.2];
 * 描  述: 信息状态返回类，同意使用此类返回数据
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @AzerothAutowired
    public SysUserService sysUserService;

    @AzerothAutowired
    public SysPowerService sysPowerService;

    protected BaseService getServcie() {
        return sysUserService;
    }

    protected String getJumpData() {
        return "";
    }

    /**
     * 重定向到登录页面
     * 创建人：yinquan
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "redirect/login")
    public String redirectLogin(Model model, HttpServletRequest request, HttpServletResponse response) {
        return "login/login";
    }

    /**
     * 登录请求
     * 创建人：lvjx
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value="login", method=RequestMethod.POST)
    @ResponseBody
    public Object login(Model model, HttpServletRequest request, HttpServletResponse response){

        Map<String,Object> parameters = Maps.newHashMap();

        Result result = super.isCheck(request);
        // 验证参数合法性：账户名、密码、[验证码]
        if(!result.isPass()) {
            result.resoutError(null);
            return result;
        }

        String account = request.getParameter("account");
        String password = request.getParameter("passwd");

        /*if(StringUtils.isBlank(username)){
            result.setCode(Constant.SESSION_KEY.CODE_100);
            return json;
        }else if(StringUtils.isBlank(password)){
            json.setErrcode(ConstantCode.CODE_ERR_995);
            return json;
        }*/

        //查询登录用户是否存在
        parameters.put("account", account);
        parameters.put("password", MD5Util.getMD5Code(password));
        SysUserEntity sysUserEntity = sysUserService.findUniqueBy(parameters);
        if(sysUserEntity == null){
            // 管理员不存在
            result.resoutError(Constant.CODE_103, result.unExist("管理员"));
            return result;

        }else if(sysUserEntity.getUseStatus().equals("0")){
            // 管理员被冻结
            result.resoutError(Constant.CODE_302, Constant.MSG_ERROR_LOCK);
            return result;
        }

        // 将管理员信息保存到 session 中
        WebUserBean webUser = new WebUserBean();
        webUser.setUid(sysUserEntity.getUid()); //uid .setAppUserId(sysUserEntity.getAppUserId());
        webUser.setLockStatus(sysUserEntity.getUseStatus()); // 锁定状态.setFreezeStatus(anAppUserEntity.getFreezeStatus());
        webUser.setName(sysUserEntity.getRealName()); // 昵称
        webUser.setNickname(sysUserEntity.getName()); //
        webUser.setSex(sysUserEntity.getSex()); // 性别姓名
        //webUser.setManageClassify(sysUserEntity.get); // 管理员类别
        webUser.setAccount(sysUserEntity.getAccount()); // 账户
        //webUser.setLastLoginAt(); // 最后一次登录时间

        HttpSession httpSession = request.getSession(true);
        httpSession.setAttribute(Constant.SESSION_KEY, webUser);

        // 获取菜单资源
        getMenuDate(sysUserEntity.getUid());

        result.resoutSucess(null, webUser);
        return result;
    }

    /** 获取所有菜单功能的 key - value **/
    private void getMenuDate(String uid) {
        // 获取基础数据
        //if(StaticData.MENU_POWER.size() == 0) {
            List<Map<String, Object>> list = sysPowerService.pageMenuDataList();
            for(int i=0, l=list.size(); i<l; i++) {
                Map<String, Object> map = list.get(i);
                StaticData.MENU_POWER.put(map.get("uid").toString(), map.get("funName"));
            }
        //}

        Map<String,Object> parameters = Maps.newHashMap();
        parameters.put("userUid", uid);
        // 获取当前用户权限数据
        List<Map<String, Object>> listPower = sysPowerService.pagePowerDataList(parameters);
        for(int i=0, l=listPower.size(); i<l; i++) {
            Map<String, Object> map = listPower.get(i);
            if(map.get("url") != null) {
                StaticData.MENU_POWER_URL.put(map.get("url").toString(), map);
            }
        }
    }
}
